/**
 * Project Name:fastPlat
 * File Name:AdminUserServiceImpl.java
 * Package Name:com.fast.user.service.admin.impl
 * Date:2014年9月11日下午4:37:14
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.user.service.admin.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.security.StringEncrypt;
import com.fast.base.util.LogUtils;
import com.fast.base.util.StringUtils;
import com.fast.base.util.data.DataRever;
import com.fast.base.util.data.UUIDHexGenerator;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.cms.service.article.ArticleService;
import com.fast.cms.service.article.NoticeInfoService;
import com.fast.user.dto.TodoListCountDTO;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.service.admin.AdminUserService;
import com.fast.user.web.form.web.AdminForm;

/**
 * ClassName:AdminUserServiceImpl <br/>
 * 用途: 管理员业务服务类 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @author lushuifa242
 * @since    JDK 1.6
 * @see
 * Date:     2014年9月11日 下午4:37:14 <br/> 	 
 */
@Service("adminUserService")
public class AdminUserServiceImpl extends JpaDaoSupport implements AdminUserService {
	
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private NoticeInfoService noticeInfoService;
	
	/**
	 * @Title: AdminUserServiceImpl
	 * @Description: 如果需要使用ibatis时请一定要在此调用一次
	 * @author lushuifa
	 */
	public AdminUserServiceImpl(){
		super.setXmlName("AdminUser");
	}
	
	/**
	 * 保存管理员
	 */
	@Override
	public void saveAdminUser(AdminUser adminUser) {
		super.persist(adminUser);
	}
	
	@Override
	public AdminUser updateAdminUser(AdminUser adminUser){
		return super.merge(adminUser);
	}
	
	// 根据id删除
	@Override
	public void deleteAdminUserById(int id){
		super.removeById(AdminUser.class, id);
	}

	// 查询
	@Override
	public AdminUser getAdminUserById(int id){
		return super.query(AdminUser.class, id);
	}

	// 查询列表
	@Override
	public List<AdminUser> listAdminUser(String whereHql){
		return super.getBeanList(AdminUser.class, whereHql);
	}
	
	//登录系统
	@Override
	public AdminUser login(String userName, String password){
		AdminUser adminUser = super.query(AdminUser.class, "where userName='"+userName+"' and password='"+password+"'");
		if(null==adminUser){
			adminUser = super.query(AdminUser.class, "where mobileTel='"+userName+"' and password='"+password+"'");
		}
		return adminUser;
	}
	
	/**
	 * 标题:兼容手机号判断<br>
	 * 编写者:lushuifa
	 * 创建时间:2017年12月17日 下午5:34:41 </pre>
	 * @param
	 * @return 
	 * @see com.fast.user.service.admin.AdminUserService#isExistUser(java.lang.String)
	 */
	@Override
    public boolean isExistUser(String userName){
		long count = super.count(AdminUser.class, " where userName=?",new Object[]{userName});
		if(count==0){
			count = super.count(AdminUser.class, " where mobileTel=?",new Object[]{userName});
		}
		return count>0;
    }
    
    /**
     * 标题：increaseLoginCount <br/>
     * 作用： 增加登录登录次数    <br/>
     * @author developer-lushuifa
     * @param id
     * @since JDK 1.6
     */
    @Override
	public int increaseLoginCount(int id){
		//增加次数
		String sql = "update "+SqlGeneratorImpl.getTableName(AdminUser.class)+" set login_count=login_count+1  where id="+id+"";
		super.entityManager.createNativeQuery(sql).executeUpdate();
		//返回最新次数
		String countSql = "select login_count from "+AbstractSqlGenerator.getTableName(AdminUser.class)+" where id="+id+"";
		Query query = super.entityManager.createNativeQuery(countSql);
		return (int) query.getSingleResult();
	}
	
	/**
	 * 说明: 更新登录信息<br>
	 * 编写者:lushuifa
	 * 创建时间:2016年10月17日 下午11:07:02 </pre>
	 * @param 
	 * @return int 说明
	 */
	@Override
	public void updateLoginInfo(AdminUser adminUser){
		adminUser.setLoginCount(adminUser.getLoginCount()+1);
		adminUser.setLastLoginDate(new Date());
		super.merge(adminUser);
	}
	
	/**
	 * 删除多个管理员信息
	 * @param id
	 * @return
	 */
	@Override
	public boolean delAdminUser(String ids){
		Query query = super.getEntityManager().createNativeQuery("delete from "+AbstractSqlGenerator.getTableName(AdminUser.class)+" where id in("+ids+")");
		return query.executeUpdate()>0;
	}
	
	/**
	 * 说明:修改密码 <br>
	 * 编写者:lushuifa
	 * 创建时间:2016年10月23日 下午4:30:05 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@Override
	public ResponseData updatePassword(Map<String, String> paramMap){
		ResponseData responseData = new ResponseData();
		//先验证当前密码是否正确
		try {
			String userName = paramMap.get("userName");
			String oldPassword = paramMap.get("oldPassword");
			String newPassword = paramMap.get("newPassword");
			AdminUser adminUser = super.query(AdminUser.class, "where userName='"+userName+"' and password='"+StringEncrypt.SHA256(oldPassword)+"'");
			if(adminUser != null){
				String updateSql = "update "+AbstractSqlGenerator.getTableName(AdminUser.class)+" set password='"+StringEncrypt.SHA256(newPassword)+"' where id="+adminUser.getId();
				Query query = super.entityManager.createNativeQuery(updateSql);
				query.executeUpdate();
			}else{
				responseData.buildResult(ResponseEnum.OLD_PASSWORD_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 分页获取管理员数据
	 */
	@Override
	public PageView<AdminUser> getAdminListByPage(AdminForm adminForm) {
		PageView<AdminUser> pageView = new PageView<AdminUser>();
		LogUtils.info("getAdminList_得到管理员列表");
		try{
			int currentPage = adminForm.getPage();//当前页
	  		int pageSize = adminForm.getRows();//每页面显示多少条
	  		String userName = adminForm.getUserName();
	  		String realName = adminForm.getRealName();
	  		StringBuffer whereSql = new StringBuffer("where 1=1 ");
	  		List<String> whereVlaues = new ArrayList<String>(); 
	  		
	  		if(!adminForm.getCurUserName().equals("kaifa")){
	  			whereSql.append(" and userName<>'kaifa'");
			}
	  		
	  		if(StringUtils.isNotEmpty(userName)){
	  			whereSql.append(" and userName like '%"+userName+"%'");
	  		}
	  		
	  		if(StringUtils.isNotEmpty(realName)){
	  			whereSql.append(" and realName like '%"+realName+"%'");
	  		}
	  		
	  		if(StringUtils.isNotEmpty(adminForm.getDepartmentUUID())){
	  			whereSql.append(" and dept_uuid='"+adminForm.getDepartmentUUID()+"' ");
	  		}
	  		
	  		if(StringUtils.isNotEmpty(adminForm.getDeptName())){
	  			whereSql.append(" and dept_name='"+adminForm.getDeptName()+"' ");
	  		}
	  		
	  		if(StringUtils.isNotEmpty(adminForm.getCompanyUUID())){
	  			whereSql.append(" and company_uuid='"+adminForm.getCompanyUUID()+"' ");
	  		}
			LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
			orderBy.put("edit_time", "desc");
			orderBy.put("loginCount", "desc");
			QueryResult<AdminUser>  queryResult = super.getScrollData(AdminUser.class, (currentPage-1)*pageSize,pageSize,whereSql.toString(), whereVlaues.toArray(),orderBy);
			pageView.setPageSize(pageSize);
		    pageView.setCurrentPage(currentPage);
			pageView.setQueryResult(queryResult);
		}catch(Exception e){
			e.printStackTrace(); 
			LogUtils.error("getAdminList获取列表：",e);
		}
		LogUtils.info("getAdminList.pageView:"+pageView.toString());
		return pageView;
	}
	
	/**
	 * 更新或者保存管理员信息
	 * @param adminUser
	 * @return
	 */
	@Override
	public ResponseData saveOrUpdateAdminUser(AdminUser adminUser){
		ResponseData responseData = new ResponseData();
		String deptNameV = adminUser.getDeptName();
		if (StringUtils.isNotBlank(deptNameV)) {
			if(deptNameV.indexOf("@")>0){
				adminUser.setDeptUUID(deptNameV.split("@")[0]);
				adminUser.setDeptName(deptNameV.split("@")[1]);
			}
		}
		
		String groupV = adminUser.getGroupName();
		if (StringUtils.isNotBlank(groupV)) {
			if(groupV.indexOf("@")>0){
				adminUser.setGroupId(DataRever.getInt(groupV.split("@")[0]));
				adminUser.setGroupName(groupV.split("@")[1]);
			}
		}
		
		
		String positionV = adminUser.getPositionName();
		if (StringUtils.isNotBlank(positionV)) {
			if (positionV.indexOf("@") > 0) {
				adminUser.setPositionUUID(positionV.split("@")[0]);
				adminUser.setPositionName(positionV.split("@")[1]);
			} 
		}
		LogUtils.info("eidtAdmin param adminUser:"+adminUser.toString());
		if (adminUser.getId() < 1) {
			//核查用户名是否存在
			boolean isExist = this.isExistUser(adminUser.getUserName());
			if(isExist){
				responseData.buildResult(ResponseEnum.EXIST_USERNAME);
				return responseData;
			}
			//设定默认密码8个8
			adminUser.setUuid(UUIDHexGenerator.generator());
			adminUser.setPassword(StringEncrypt.SHA256("88888888"));
			responseData.setMsg("新增用户【"+adminUser.getUserName()+"】成功，默认密码为8个8,请通知他(她)登录系统修改密码!");
		}else{
			AdminUser _adminUser = this.query(AdminUser.class, adminUser.getId());
			adminUser.setPassword(_adminUser.getPassword());
			responseData.setMsg("修改【"+adminUser.getUserName()+"】用户成功！");
		}
		// 当存在UUID时的处理
		responseData.setData(this.merge(adminUser));
		return responseData;
	}
	
	/**
	 * 统计代办事项
	 * @param adminId
	 * @param adminUUID
	 * @return
	 */
	@Override
	public TodoListCountDTO queryTodoListCount(int adminId, String adminUUID) {
		TodoListCountDTO todoListCount = new TodoListCountDTO();
		int checkDocCount = 0;
		todoListCount.setCheckDocCount(checkDocCount);
		int checkNoticeCount = this.noticeInfoService.queryCheckNoticeCount(adminId);
		todoListCount.setCheckNoticeCount(checkNoticeCount);
	    int checkArticleCount = this.articleService.queryCheckArticleCount(adminId);
	    todoListCount.setCheckArticleCount(checkArticleCount);
		return todoListCount;
	}
	
	/**
	 * 说明:重置管理员密码 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年11月9日 上午12:01:25 </pre>
	 * @param 
	 * @return boolean 操作是否成功
	 */
	@Override
	public boolean resetPassword(String ids){
		String password = StringEncrypt.SHA256("88888888");
		Query query = super.getEntityManager().createNativeQuery("update "+AbstractSqlGenerator.getTableName(AdminUser.class)+" set password='"+password+"' where id in("+ids+")");
		return query.executeUpdate()>0;
	}
	
	/**
	 * 查询管理员信息
	 */
	@Override
	public AdminUser queryAdminInfoByMobile(String mobile){
		return super.query(AdminUser.class, "where mobileTel='"+mobile+"'");
	}
	
	/**
	 * 说明: 根据uuid获取管理员信息<br>
	 * 编写者:lushuifa
	 * 创建时间:2018年4月16日 下午11:24:00 </pre>
	 * @param 
	 * @return AdminUser 说明
	 */
	@Override
	public AdminUser getAdminUserByUUID(String uuid) {
		return super.queryForBeanByUUID(AdminUser.class,uuid);
	}
}

